//
//  DynamicTools.m
//  ZZKitDemo
//
//  Created by hfzhangzhang on 2018/8/8.
//  Copyright © 2018年 hfzhangzhang. All rights reserved.
//

#import "DynamicTools.h"

@implementation DynamicTools

void Swizzle_(Class c, SEL origSEL, SEL sizSEL) {
    
    Method origMethod = class_getInstanceMethod(c, origSEL);
    
    Method newMethod = nil;
    
    if (!origMethod) {
        
        origMethod = class_getClassMethod(c, origSEL);
        if (!origMethod) {
            return;
        }
        newMethod = class_getClassMethod(c, sizSEL);
        if (!newMethod) {
            return;
        }
    }else{
        newMethod = class_getInstanceMethod(c, sizSEL);
        if (!newMethod) {
            return;
        }
    }
    
    // 自身已经实现了这个方法 就添加不成功，直接交换即可
    if(class_addMethod(c, origSEL, method_getImplementation(newMethod), method_getTypeEncoding(newMethod))){
        
        class_replaceMethod(c, sizSEL, method_getImplementation(origMethod), method_getTypeEncoding(origMethod));
        
    }else{
        method_exchangeImplementations(origMethod, newMethod);
    }
}
@end
